package com.version1.diabeco.data.comida;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.version1.diabeco.data.AbstractDao;
import com.version1.diabeco.data.DiabecoContract;
import com.version1.diabeco.model.alimento.Alimento;

public final class AlimentoDaoImpl extends AbstractDao implements AlimentoDao {

	private Context context;

	private static AlimentoDaoImpl instance;

	private AlimentoDaoImpl(Context context) {
		super(context);
	}

	/**
	 * Retrieves the singleton instance. Receives a context which is used for database initialization but also stored
	 * for subsequent sql operation calls.
	 * 
	 * This method is thread-safe.
	 * 
	 * @return AlimentoDao with the instance.
	 */
	public static synchronized AlimentoDaoImpl getInstance(Context context) {
		if (instance == null) {
			instance = new AlimentoDaoImpl(context);
		}

		instance.setContext(context);

		return instance;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	@Override
	public Long count() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Alimento selectById(Long id) {

		Alimento result = null;

		SQLiteDatabase db = AlimentoDaoImpl.getInstance(this.getContext()).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection = { DiabecoContract.Alimento._ID,
				DiabecoContract.Alimento.COLUMNA_NOMBRE,
				DiabecoContract.Alimento.COLUMNA_HDECARBONO };

		String selection = DiabecoContract.Alimento._ID + " = ?";
		String[] selectionArgs = { id.toString() };

		// How you want the results sorted in the resulting Cursor
		String sortOrder = DiabecoContract.Alimento.COLUMNA_NOMBRE + " ASC";

		Cursor cursor = db.query(DiabecoContract.Alimento.TABLE_NAME, // The table to query
				projection, // The columns to return
				selection, // The columns for the WHERE clause
				selectionArgs, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);

		cursor.moveToFirst();
		result = this.toDomainObjectList(cursor);

		return result;

	}

	@Override
	public List<Alimento> selectBetweenDates(Date from, Date to) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Alimento> selectAll() {
		List<Alimento> result = new ArrayList<Alimento>();

		SQLiteDatabase db = AlimentoDaoImpl.getInstance(this.getContext()).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection = { DiabecoContract.Alimento._ID,
				DiabecoContract.Alimento.COLUMNA_NOMBRE,
				DiabecoContract.Alimento.COLUMNA_HDECARBONO };

		String selection = null;
		String[] selectionArgs = null;

		// How you want the results sorted in the resulting Cursor
		String sortOrder = DiabecoContract.Alimento.COLUMNA_NOMBRE + " ASC";

		Cursor cursor = db.query(DiabecoContract.Alimento.TABLE_NAME, // The table to query
				projection, // The columns to return
				selection, // The columns for the WHERE clause
				selectionArgs, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);

		while (cursor.moveToNext()) {
			Alimento alimento = this.toDomainObjectList(cursor);
			result.add(alimento);
		}

		return result;
	}

	public void save(Alimento alimento) {

		// Gets the data repository in write mode
		SQLiteDatabase db = AlimentoDaoImpl.getInstance(this.getContext()).getWritableDatabase();

		// Create a new map of values, where column names are the keys
		ContentValues values = new ContentValues();
		values.put(DiabecoContract.Alimento.COLUMNA_NOMBRE, alimento.getNombre());
		values.put(DiabecoContract.Alimento.COLUMNA_HDECARBONO, alimento.getCarbohidratos());

		// Insert the new row, returning the primary key value of the new row
		long newRowId;
		newRowId = db.insert(DiabecoContract.Alimento.TABLE_NAME, null, values);

		System.out.println("Registros grabados en la base de datos: " + newRowId);

	}

	@Override
	public void deleteById(Long id) {

		// Gets the data repository in write mode
		SQLiteDatabase db = AlimentoDaoImpl.getInstance(this.getContext()).getWritableDatabase();

		String removeId = id.toString();

		int rowsDeleted = db.delete(DiabecoContract.Alimento.TABLE_NAME, DiabecoContract.Alimento._ID
				+ "=?", new String[] { removeId });

		if (rowsDeleted != 1) {
			throw new RuntimeException("No se pudo eliminar el registro con id " + id);
		}

	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

	private Alimento toDomainObjectList(Cursor cursor) {
		Alimento alimento = new Alimento();

		Long id = cursor.getLong(cursor.getColumnIndexOrThrow(DiabecoContract.Alimento._ID));
		String nombre = cursor.getString(cursor
				.getColumnIndexOrThrow(DiabecoContract.Alimento.COLUMNA_NOMBRE));
		Long hdecarbono = cursor.getLong(cursor
				.getColumnIndexOrThrow(DiabecoContract.Alimento.COLUMNA_HDECARBONO));

		alimento.setId(id);
		alimento.setNombre(nombre);
		alimento.setCarbohidratos(hdecarbono);

		System.out.println("Readed food intake measure: " + alimento);

		return alimento;
	}

}
